var iCertifications = 1;
var dataSource;
var comboMoes;
var urlMoes = appBosch.getMoes;
var managers = [
    { text: "Gerente MOE", value: 2 },
    { text: "Supervisor de entrenamiento", value: 3 }
];
if (appBosch.isRHManager == 0) {
    managers[managers.length] = {text: "Gerente RH", value: 1};
}

$(document).ready(function() {
    var grid = $('#grid');
    grid.on('click', '.seeImage', verImagen);
    dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: appBosch.crud.read,
                dataType: "json"
            },
            create: {
                url: appBosch.crud.create,
                dataType: "json"
            },
            update: {
                url: appBosch.crud.update,
                dataType: "json"
            },
            destroy: {
                url: appBosch.crud.destroy,
                dataType: "json"
            },
            parameterMap: function(options, operation) {
                var params = {};
                switch (operation)
                {
                    case 'create':
                        params = {models: kendo.stringify(options.models)};
                        if (options.models[0].type == 1) {
                            managers.splice(2, 1);
                        }
                        break;
                    case 'read':
                        break;
                    case 'update':
                        params = {models: kendo.stringify(options.models)};
                        if (options.models[0].type == 1) {
                            managers.splice(2, 1);
                        }
                        break;
                    case 'destroy':
                        params = {id: options.models[0].value};
                        if (options.models[0].type == 1) {
                            managers[managers.length] = {text: "Gerente RH", value: 1};
                        }
                }
                return params;
            }
        },
        requestEnd: function (e) {
            if((e.type == "create" || e.type == "update") && e.response == false) {
                dataSource.cancelChanges();
                alert('Ya existe un gerente del mismo tipo para este MOE');
            }
        },
        batch: true,
        schema: {
            model: {
                id: "value",
                fields: {
                    moeId: {
                        type: 'string'
                    },
                    userId: {
                        type: 'string'
                    },
                    moeN: {
                        type: 'string'
                    },
                    userN: {
                        type: 'string'
                    },
                    sign: {
                        type: 'string'
                    },
                    job: {
                        type: 'string'
                    },
                    type: {
                        type: 'number'
                    }
                }
            }
        }
    });

    grid.kendoGrid({
        toolbar: [
            {
                name: 'create',
                text: 'Agregar gerente'
            },
            {
                name: "pdf",
                text: "Exportar a PDF"
            },
            {
                name: "excel",
                text: "Exportar a Excel"
            }
        ],
        excel: {
            fileName: "Gerentes.xlsx",
            filterable: true,
            allPages: true
        },
        pdf: {
            allPages: true,
            fileName: "Gerentes.pdf"
        },
        scrollable: true,
        filterable: true,
        selectable: true,
        navigatable: true,
        resizable: true,
        columnMenu: true,
        sortable: true,
        dataSource: dataSource,
        groupable: true,
        dataBound: function () {
            iCertifications = 1;
        },
        columns: [
            {
                title: "#",
                template: '#=iCertifications++#',
                width:50
            },
            {
                field: "job",
                title: "Puesto",
                editor: editorJob
            },
            {
                field: "moeId",
                title: "MOE",
                template: '#= moeId == null ? "N/A" : moeN#',
                editor: editorMoes
            },
            {
                field: "userId",
                title: "Usuario",
                template: '#=userN#',
                editor: editorUser
            },
            {
                field: "sign",
                title: "Firma",
                editor: imgEditor,
                template: '#if(sign !== "0" && sign !== "" && sign !== null && sign !== undefined){# <button class="seeImage k-button k-button-icontext">Ver imagen</button>#}#',
                width: 150
            },
            {
                command: [
                    {
                        name: "edit",
                        text: {
                            edit: "",
                            update: "",
                            cancel: ""
                        }
                    },
                    {
                        name: "destroy",
                        text: ""
                    }
                ],
                title: "&nbsp;"
            }
        ],
        editable: 'inline'
    }).data('kendoGrid');
});

function editorMoes(container, options) {
    var input = $("<input id='comboMoes'/>");
    input.attr("name", options.field);
    input.appendTo(container);
    comboMoes = input.kendoDropDownList({
        autoBind: false,
        dataTextField: "text",
        dataValueField: "value",
        dataSource: new kendo.data.DataSource({
            serverFiltering: true,
            transport: {
                read: {
                    url: appBosch.getMoes,
                    dataType: "json"
                }
            }
        }),
        change: function() {
            options.model.moeId = this.value();
            options.model.moeN = this.text();
        }
    }).data('kendoDropDownList');
}

function editorUser(container, options) {
    var input = $('<input />');
    input.attr("name", options.field);
    input.appendTo(container);
    input.kendoDropDownList({
        dataTextField: "text",
        dataValueField: "value",
        dataSource: new kendo.data.DataSource({
            serverFiltering: true,
            transport: {
                read: {
                    url: appBosch.getUsers,
                    dataType: "json"
                }
            }
        }),
        change: function() {
            options.model.userId = this.value();
            options.model.userN = this.text();
        }
    });
}

function editorJob(container, options) {
    var input = $('<input id="jobDDL" />');
    input.attr("name", options.field);
    input.appendTo(container);
    input.kendoDropDownList({
        dataTextField: "text",
        dataValueField: "text",
        dataSource: managers,
        change: function () {
            var dataItem = this.dataItem();
            options.model.type = dataItem.value;
            if (dataItem.value == 1) {
                comboMoes.dataSource.transport.options.read.url = urlMoes + '/1';
            } else {
                comboMoes.dataSource.transport.options.read.url = urlMoes;
            }
            comboMoes.dataSource.read();
        }
    });
}

function imgEditor(container, options) {
    var input = $("<input type='file' id='image' />");
    input.attr("name", options.field);
    input.appendTo(container);
    input.kendoUpload({
        async: {
            saveUrl: appBosch.upload
        },
        localization: {
            select: "Seleccionar...",
            headerStatusUploaded: "",
            headerStatusUploading: "",
            statusUploaded: "",
            statusUploading: ""
        },
        success: function () {
            options.model.set('sign', 'Ok');
        },
        multiple: false
    });
}

function verImagen (e) {
    var dataItem = $(e.currentTarget).closest("tr");
    dataItem = dataSource.getByUid(dataItem.data('uid'));
    $("<div><img src='../" + dataItem.sign + "?" + Math.floor((Math.random() * 10) + 1).toString() + "' width='400px' /></div>").kendoWindow({
        width: "400px",
        title: "Imagen",
        actions: [
            "Close"
        ]
    }).data("kendoWindow").open().center();
}